using System;
using System.Windows;
using System.Windows.Controls;
namespace Microsoft.Phone.Controls.Primitives
{
	public class TemplatedListBox : ListBox
	{
		public event EventHandler<LinkUnlinkEventArgs> Link;
		public event EventHandler<LinkUnlinkEventArgs> Unlink;
		public DataTemplate ListHeaderTemplate
		{
			get;
			set;
		}
		public DataTemplate ListFooterTemplate
		{
			get;
			set;
		}
		public DataTemplate GroupHeaderTemplate
		{
			get;
			set;
		}
		public DataTemplate GroupFooterTemplate
		{
			get;
			set;
		}
		protected override DependencyObject GetContainerForItemOverride()
		{
			return new TemplatedListBoxItem();
		}
		protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
		{
			base.PrepareContainerForItemOverride(element, item);
			DataTemplate contentTemplate = null;
			LongListSelectorItem longListSelectorItem = item as LongListSelectorItem;
			if (longListSelectorItem != null)
			{
				switch (longListSelectorItem.ItemType)
				{
				case LongListSelectorItemType.Item:
					contentTemplate = base.get_ItemTemplate();
					break;
				case LongListSelectorItemType.GroupHeader:
					contentTemplate = this.GroupHeaderTemplate;
					break;
				case LongListSelectorItemType.GroupFooter:
					contentTemplate = this.GroupFooterTemplate;
					break;
				case LongListSelectorItemType.ListHeader:
					contentTemplate = this.ListHeaderTemplate;
					break;
				case LongListSelectorItemType.ListFooter:
					contentTemplate = this.ListFooterTemplate;
					break;
				}
				TemplatedListBoxItem templatedListBoxItem = (TemplatedListBoxItem)element;
				templatedListBoxItem.set_Content(longListSelectorItem.Item);
				templatedListBoxItem.Tuple = longListSelectorItem;
				templatedListBoxItem.set_ContentTemplate(contentTemplate);
				ContentPresenter firstLogicalChildByType = templatedListBoxItem.GetFirstLogicalChildByType(true);
				EventHandler<LinkUnlinkEventArgs> link = this.Link;
				if (firstLogicalChildByType != null && link != null)
				{
					link.Invoke(this, new LinkUnlinkEventArgs(firstLogicalChildByType));
				}
			}
		}
		protected override void ClearContainerForItemOverride(DependencyObject element, object item)
		{
			LongListSelectorItem longListSelectorItem = item as LongListSelectorItem;
			if (longListSelectorItem != null)
			{
				ContentPresenter firstLogicalChildByType = ((FrameworkElement)element).GetFirstLogicalChildByType(true);
				EventHandler<LinkUnlinkEventArgs> unlink = this.Unlink;
				if (firstLogicalChildByType != null && unlink != null)
				{
					unlink.Invoke(this, new LinkUnlinkEventArgs(firstLogicalChildByType));
				}
			}
			base.ClearContainerForItemOverride(element, item);
		}
	}
}
